package tianhao.luo.algorithm;

/**
 * 暴力匹配算法
 *
 * @author: tianhao.luo@hand-china.com 2021/6/30  下午9:45
 */
public class ViolenceMatch {

    private String str1;

    private String str2;

    public ViolenceMatch(String str1, String str2) {
        this.str1 = str1;
        this.str2 = str2;
    }

    public int violenceMatch() {
        char[] s1 = str1.toCharArray();
        char[] s2 = str2.toCharArray();

        int s1Len = s1.length;
        int s2Len = s2.length;

        //i索引指向s1
        int i = 0;
        //j索引指向s2
        int j = 0;

        // 保证匹配时不越界
        // 两个字符串,其中一个遍历完毕表示走完整个匹配流程,无需继续
        while (i < s1Len && j < s2Len) {
            // 匹配成功时,s1和s2的指针后移
            if (s1[i] == s2[j]){
                i++;
                j++;
            }else {
                // 匹配失败时,需要将i回到起始位置并+1,j置零
                i = i -j +1;
                j =0;
            }
        }

        // 判断是否匹配成功
        if (j == s2Len){
            return i -j;
        }else{
            return -1;
        }
    }
}
